package com.irdstudio.efp.batch.service.impl.bd;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.MonAlrmLvlEnums.MonAlrmLvlEnum;
import com.irdstudio.basic.framework.core.util.DateTool;
import com.irdstudio.efp.batch.service.facade.bd.BdRepayDetailBatchService;
import com.irdstudio.efp.batch.service.util.DueDataUtil;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.facade.AccoutErroTempService;
import com.irdstudio.efp.loan.service.facade.BdRepayDetailService;
import com.irdstudio.efp.loan.service.facade.BdRepayDetailTempService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.loan.service.vo.AccoutErroTempVO;
import com.irdstudio.efp.loan.service.vo.BdRepayDetailTempVO;
import com.irdstudio.efp.loan.service.vo.BdRepayDetailVO;
import com.irdstudio.efp.nls.service.facade.BdLoanpayService;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;

/**
 * 
 * 根据百度同步过来的还款明细分期临时表数据修改还款明细分期表
 * 
 * @author ludayong
 * @since 2019年3月7日 下午3:18:50
 * @version 1.0
 */
@Service("bdRepayDetailBatchService")
public class BdRepayDetailBatchServiceImpl implements BdRepayDetailBatchService, FrameworkService {

	private static Logger logger = LoggerFactory.getLogger(BdRepayDetailBatchServiceImpl.class);

	@Autowired
	@Qualifier("bdRepayDetailTempService")
	private BdRepayDetailTempService bdRepayDetailTempService;// 还款明细分期临时信息

	@Autowired
	@Qualifier("bdRepayDetailService")
	private BdRepayDetailService bdRepayDetailService;// 还款明细分期信息

	@Autowired
	@Qualifier("accLoanService")
	private AccLoanService accLoanService;// 借据信息

	@Autowired
	@Qualifier("accoutErroTempService")
	private AccoutErroTempService accoutErroTempService;// 错误信息

	// @Autowired
	// @Qualifier("bdDnDetailTempService")
	// private BdDnDetailTempService bdDnDetailTempService;// 放款明细临时信息
	@Autowired
	@Qualifier("bdLoanpayService")
	private BdLoanpayService bdLoanpayService;// 百度放款通知记录信息

	@Autowired
	@Qualifier("nlsApplyInfoService")
	private NlsApplyInfoService nlsApplyInfoService;// 网贷申请信息

	/**
	 * 
	 * 根据百度同步过来的还款明细分期临时表数据修改还款明细分期表 <br>
	 * 0.1:ludayong:2019年3月7日 下午3:17:41:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月7日 下午3:17:41
	 * @date 2019年3月7日 下午3:17:41
	 * @version 0.1
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean batchUpdateRepayDetail() throws Exception {
		boolean result = false;
		long startTime = System.currentTimeMillis();
		logger.info("同步百度还款明细分期临时数据到还款明细分期表：[" + DateTool.formatDate(new Date(startTime), DateTool.PATTERN_DATETIME) + "]， 处理开始");
		// 可以配置参数
		Integer pageSize = 1000;
		try {
			// 需要新增或者修改的还款明细分期信息
			List<BdRepayDetailTempVO> list = null;
			// 分页信息
			BdRepayDetailTempVO pageInfo = new BdRepayDetailTempVO();
			// 新增或者修改的还款明细分期信息数量
			int num = 0;
			// 页数
			int page = 1;
			// pageSize初始化
			if (pageSize > 0) {
				pageInfo.setSize(pageSize);
			} else {
				pageInfo.setSize(1000);
			}
			// 判断循环次数
			int size = bdRepayDetailTempService.queryCount();
			String size_msg = "【还款明细分期临时表】数据量：" + size;
			logger.info(size_msg, "message{}");
			int loopCount = (size / pageInfo.getSize()) + 1;
			// 放款信息
			// BdDnDetailTempVO inBdDnDetailTempVO = new BdDnDetailTempVO();
			// 百度放款通知记录信息
			// BdLoanpayVO inBdLoanpayVO = new BdLoanpayVO();
			// 网贷申请基本信息
			// NlsApplyInfoVO inNlsApplyInfoVO = new NlsApplyInfoVO();
			// 借据信息
			AccLoanVO inAccLoanVO = new AccLoanVO();
			// 借据号
			// String bdLoanId = null;
			for (int i = 0; i < loopCount; i++) {
				String page_msg = "【还款明细分期临时表】当前页数：" + pageInfo.getPage() + "，分页大小：" + pageInfo.getSize();
				logger.info(page_msg, "message{}");
				// 分页查询【还款明细表】数据
				List<BdRepayDetailTempVO> tempList = bdRepayDetailTempService.queryByPage(pageInfo);
				list = new ArrayList<BdRepayDetailTempVO>();
				if (Objects.nonNull(tempList) && !tempList.isEmpty()) {
					for (BdRepayDetailTempVO bdRepayDetailTempVO : tempList) {
						// bdLoanId = bdRepayDetailTempVO.getLoanId();
						// 放款明细入参
						// inBdDnDetailTempVO.setLoanId(bdLoanId);
						// 查询的放款信息
						// BdDnDetailTempVO queryBdDnDetailTempVO =
						// bdDnDetailTempService.queryByPk(inBdDnDetailTempVO);
						// 百度放款通知记录信息
						// inBdLoanpayVO.setLoanId(bdLoanId);
						// 查询百度放款通知记录信息
						// BdLoanpayVO queryBdLoanpayVO = bdLoanpayService.queryByPk(inBdLoanpayVO);
						// String orderId = "";
						// if (Objects.nonNull(queryBdLoanpayVO)) {
						// // 订单号
						// orderId = queryBdLoanpayVO.getOrderId();
						// } else {
						// String tableName = "bd_loanpay";
						// String errorMsg = "未查询到还款明细分期信息关联的百度放款通知记录信息，借据号：" + bdLoanId;
						// addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg,
						// errorMsg);
						// logger.error(errorMsg);
						// }
						// 网贷用信申请流水号
						// String applySeq = "";
						// 订单号非空
						// if (!StringUtil.isNullorBank(orderId)) {
						// // 订单号
						// inNlsApplyInfoVO.setBdOrderId(orderId);
						// // 查询的网贷申请基本信息
						// NlsApplyInfoVO queryNlsApplyInfoVO =
						// nlsApplyInfoService.queryByPk(inNlsApplyInfoVO);
						// if (Objects.nonNull(queryNlsApplyInfoVO)) {
						// // 网贷用信申请流水号
						// applySeq = queryNlsApplyInfoVO.getApplySeq();
						// } else {
						// String tableName = "nls_apply_info";
						// String errorMsg = "未查询到还款明细分期信息关联的网贷申请基本信息，放款订单号：" + orderId + "，借据号：" +
						// bdLoanId;
						// addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg,
						// errorMsg);
						// logger.error(errorMsg);
						// }
						// }
						// 网贷用信申请流水号非空
						// if (!StringUtil.isNullorBank(applySeq)) {
						// 设置借据号
						inAccLoanVO.setBillNo(bdRepayDetailTempVO.getLoanId());
						AccLoanVO queryAccLoanVo = accLoanService.queryByPk(inAccLoanVO);
						// 1.1根据还款明细分期临时信息的借据号查询借据信息是否存在，存在：进行下一步操作，不存在：记录异常信息
						if (Objects.nonNull(queryAccLoanVo)) {
							bdRepayDetailTempVO = initBdRepayDetailInfo(bdRepayDetailTempVO, queryAccLoanVo.getPrdCode());
							// 需要新增或者修改的还款明细分期信息
							list.add(bdRepayDetailTempVO);
						} else {
							String tableName = "acc_loan";
							String errorMsg = "未查询到还款明细分期信息关联的借据信息";
							addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, errorMsg);
							logger.error(errorMsg);
						}
						// }
					}
					// 需要新增或者修改的还款明细分期信息
					if (Objects.nonNull(list) && !list.isEmpty()) {
						List<BdRepayDetailVO> bdRepayDetailList = new ArrayList<BdRepayDetailVO>();
						bdRepayDetailList = (List<BdRepayDetailVO>) beansCopy(list, BdRepayDetailVO.class);
						int updateSize = bdRepayDetailService.insertOrUpdateBdRepayDetail(bdRepayDetailList);
						num += updateSize;
					}
				}
				pageInfo.setPage(++page);
			}
			String num_msg = "【还款明细分期表】插入或更新数据处理结果:" + num;
			logger.info(num_msg, "message{}");
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			String tableName = "bd_repay_detail";
			String errorMsg = "同步百度还款明细分期临时数据到还款明细分期表出错";
			String remark = "同步百度还款明细分期临时数据到还款明细分期表出错，错误信息：" + e.getMessage();
			addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, remark);
			logger.error(remark);
			throw new Exception(remark);
		}
		long endTime = System.currentTimeMillis();
		logger.info("同步百度还款明细分期临时数据到还款明细分期表：[" + DateTool.formatDate(new Date(endTime), DateTool.PATTERN_DATETIME) + "]， 处理结束");
		logger.info("同步百度还款明细分期临时数据到还款明细分期表，耗时：[" + (endTime - startTime) / 1000.0 + "]秒，处理结果[" + result + "]");
		return result;
	}

	/**
	 * 
	 * 根据还款明细分期临时信息的借据号查询还款明细分期正式表信息是否存在 <br>
	 * 0.1:ludayong:2019年3月8日 上午9:03:27:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月8日 上午9:03:27
	 * @date 2019年3月8日 上午9:03:27
	 * @version 0.1
	 */
	public boolean queryBdRepayDetailInfo(BdRepayDetailTempVO bdRepayDetailTempVO) {
		boolean isExit = false;
		BdRepayDetailVO inBdRepayDetailVo = new BdRepayDetailVO();
		if (Objects.nonNull(bdRepayDetailTempVO)) {
			inBdRepayDetailVo.setSeqNo(bdRepayDetailTempVO.getSeqNo());
			// 查询还款明细分期正式表信息是否存在
			BdRepayDetailVO queryBdRepayDetailVO = bdRepayDetailService.queryByPk(inBdRepayDetailVo);
			if (Objects.nonNull(queryBdRepayDetailVO)) {
				isExit = true;
			}
		}
		return isExit;
	}

	/**
	 * 
	 * 初始化还款明细分期正式表信息 <br>
	 * 0.1:ludayong:2019年3月8日 上午9:03:27:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月8日 上午9:03:27
	 * @date 2019年3月8日 上午9:03:27
	 * @version 0.1
	 * @throws Exception
	 */
	public BdRepayDetailTempVO initBdRepayDetailInfo(BdRepayDetailTempVO bdRepayDetailTempVO, String prdCode) {
		// 单位转换
		final int oneHundred = 100;
		// cur_date 账务日期
		bdRepayDetailTempVO.setCurDate(DueDataUtil.dateInfoTrans(bdRepayDetailTempVO.getCurDate()));
		// tran_date 交易日期
		bdRepayDetailTempVO.setTranDate(DueDataUtil.dateInfoTrans(bdRepayDetailTempVO.getTranDate()));
		// tran_time 交易时间
		String tranTime = "";
		try {
			tranTime = DueDataUtil.formatTime6To8(bdRepayDetailTempVO.getTranTime());
		} catch (Exception e) {
			logger.error("时间转换出现异常，异常信息：" + e.getMessage());
		}
		bdRepayDetailTempVO.setTranTime(tranTime);
		// event 交易事件
		bdRepayDetailTempVO.setEvent(bdRepayDetailTempVO.getEvent());
		// 设置新的借据号
		// bdRepayDetailTempVO.setLoanId(loanId);
		// total_amt 交易金额 Number 单位：分
		bdRepayDetailTempVO.setTotalAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getTotalAmt(), oneHundred));
		// int_reduced_amt_coupon 优惠券抵扣利息金额 Number 单位：分
		bdRepayDetailTempVO.setIntReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getIntReducedAmtCoupon(), oneHundred));
		// pnlt_reduced_amt_coupon 优惠券抵扣罚息金额 Number 单位：分
		bdRepayDetailTempVO
				.setPnltReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getPnltReducedAmtCoupon(), oneHundred));
		// fund_fee_reduced_amt_coupon 优惠券抵扣借款服务费金额 Number 单位：分
		bdRepayDetailTempVO
				.setFundFeeReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getFundFeeReducedAmtCoupon(), oneHundred));
		// income_amt 实收金额 Number 单位：分
		bdRepayDetailTempVO.setIncomeAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getIncomeAmt(), oneHundred));
		// prin_amt 本金发生额 Number 单位：分
		bdRepayDetailTempVO.setPrinAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getPrinAmt(), oneHundred));
		// int_amt 利息发生额 Number 单位：分
		bdRepayDetailTempVO.setIntAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getIntAmt(), oneHundred));
		// pnlt_int_amt 罚息发生额 Number 单位：分
		bdRepayDetailTempVO.setPnltIntAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getPnltIntAmt(), oneHundred));
		// fund_fee_amt 借款服务费发生额 Number 单位：分
		bdRepayDetailTempVO.setFundFeeAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getFundFeeAmt(), oneHundred));
		// charges_reduced_amt_coupon 优惠券抵扣分期手续费 Number 单位：分
		bdRepayDetailTempVO
				.setChargesReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getChargesReducedAmtCoupon(), oneHundred));
		// overdue_reduced_amt_coupon 优惠券抵扣逾期费 Number 单位：分
		bdRepayDetailTempVO
				.setOverdueReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getOverdueReducedAmtCoupon(), oneHundred));
		// repay_violate_reduced_amt_coupon 优惠券抵扣提前还款违约金 Number 单位：分
		bdRepayDetailTempVO.setRepayViolateReducedAmtCoupon(
				DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getRepayViolateReducedAmtCoupon(), oneHundred));
		// refund_violate_reduced_amt_coupon 优惠券抵扣退款违约金 Number 单位：分
		bdRepayDetailTempVO.setRefundViolateReducedAmtCoupon(
				DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getRefundViolateReducedAmtCoupon(), oneHundred));
		// service_reduced_amt_coupon 优惠券抵扣担保费 Number 单位：分
		bdRepayDetailTempVO
				.setServiceReducedAmtCoupon(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getServiceReducedAmtCoupon(), oneHundred));
		// charges_amt 分期手续费发生额 Number 单位：分
		bdRepayDetailTempVO.setChargesAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getChargesAmt(), oneHundred));
		// overdue_amt 逾期费发生额 Number 单位：分
		bdRepayDetailTempVO.setOverdueAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getOverdueAmt(), oneHundred));
		// repay_violate_amt 提前还款违约金发生额 Number 单位：分
		bdRepayDetailTempVO.setRepayViolateAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getRepayViolateAmt(), oneHundred));
		// refund_violate_amt 退款违约金发生额 Number 单位：分
		bdRepayDetailTempVO.setRefundViolateAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getRefundViolateAmt(), oneHundred));
		// service_amt 担保费发生额 Number 单位：分
		bdRepayDetailTempVO.setServiceAmt(DueDataUtil.checkDecimalInfo(bdRepayDetailTempVO.getServiceAmt(), oneHundred));
		// prd_code 产品代码
		bdRepayDetailTempVO.setPrdCode(prdCode);
		// create_time 创建时间
		bdRepayDetailTempVO.setCreateTime(DateTool.getCurrentDateTime());
		// last_modify_time 最近修改时间
		bdRepayDetailTempVO.setLastModifyTime(DateTool.getCurrentDateTime());
		return bdRepayDetailTempVO;
	}

	/**
	 * 
	 * 记录异常信息 <br>
	 * 0.1:ludayong:2019年3月8日 上午8:40:46:新增 <br>
	 * 
	 * @author ludayong
	 * @since 2019年3月8日 上午8:40:46
	 * @date 2019年3月8日 上午8:40:46
	 * @version 0.1
	 */
	private void addErrorInfo(String tableName, String errorType, String errorMsg, String remark) {
		AccoutErroTempVO accoutErroTempVO = new AccoutErroTempVO();
		// 表名
		accoutErroTempVO.setTableName(tableName);
		// 错误级别
		accoutErroTempVO.setErroType(errorType);
		// 错误信息
		accoutErroTempVO.setErroMsg(errorMsg);
		// 备注
		accoutErroTempVO.setRemark(remark);
		// 创建时间
		accoutErroTempVO.setCreateData(DateTool.getCurrentDateTime());
		// 修改时间
		accoutErroTempVO.setLastModifyTime(DateTool.getCurrentDateTime());
		// 记录异常信息
		accoutErroTempService.insert(accoutErroTempVO);
	}
}
